#!/bin/sh

# This script enables bookmarks and url handlers for surf, using sprop(1).
#
# Keybindings
# -----------
# 	^b (bookmark current url with given tags)
# 	^g (open url with bookmark autocompletion)
# 	^G (open url without bookmark autocompletion)
#
# URL handlers
# ------------
# This script implements several url handlers
# 	"d " (bookmark current url in delicious)
# 	"t " (create tinyurl from current page)
# 	"w word .." (lookup word in wikipedia)
# 	"g word .." (google for given word)
# 	"y word .." (search in youtube)
#
# Authors
# -------
# The code was originally cobbled together by Peter John Hartman, but was
# then somewhat simplified by pancake and nibble. Bastardized to use sprop
# by Andrew Antle.
#
# Installation
# ------------
# Copy the following code into a shellscript named 'spurf.sh' in $PATH. Edit
# config.h according to the rules explained forthwith.
#
# Replace default setprop with this one:
# #define SETPROP(p) { .v = (char *[]){ "/bin/sh", "-c", "spurf.sh $1 $0", p, winid, NULL } }
#
# { MODKEY, GDK_b, spawn, SETPROP("_SURF_BMARK") },
# { MODKEY|GDK_SHIFT_MASK, GDK_g, spawn, SETPROP("_SURF_URI_RAW") },

bmarks=~/.surf/bmarks
xid=$1
p=$2
uri=`sprop $xid _SURF_URI`
kw=`sprop $xid _SURF_FIND`

s_sprop() {
	[ -n "$2" ] && sprop $xid $1 "$2"
}

case "$p" in
"_SURF_FIND")
	find="`echo $kw | dmenu -p find:`"
	s_sprop _SURF_FIND "$find"
	;;
"_SURF_BMARK")
	grep "$uri" $bmarks >/dev/null 2>&1 || echo "$uri" >> $bmarks
	;;
"_SURF_URI_RAW")
	uri=`echo $uri | dmenu -p "uri:"`
	s_sprop _SURF_URI "$uri"
	;;
"_SURF_URI")
	#utd=`cat $bmarks | sort | uniq > $bmarks.$$ && mv $bmarks.$$ $bmarks`
	sel=`cat $bmarks | dmenu -p "uri [dgtwy*]:"`
	[ -z "$sel" ] && exit
	opt=`echo $sel | cut -d ' ' -f 1`
	arg=`echo $sel | cut -d ' ' -f 2-`
	case "$opt" in
	"d")
		uri="http://del.icio.us/save?url=$uri"
		;;
	"g")
		uri="http://www.google.com/search?q=$arg"
		;;
	"t")
		uri="http://tinyurl.com/create.php?url=$uri"
		;;
	"w")
		uri="http://wikipedia.org/wiki/$arg"
		;;
	"y")
		uri="http://www.youtube.com/results?search_query=$arg&aq=f"
		;;
	*)
		uri="$sel"
		;;
	esac
	s_sprop _SURF_URI "$uri"
	;;
*)
	echo Unknown xprop
	;;
esac
